package com.headline.utils;

import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

@Component
public class loginProtectInterceptor implements HandlerInterceptor {
    @Autowired
    private JwtHelper jwtHelper;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //获取token
        String token = request.getHeader("token");
        //判断token是否过期
        boolean expiration = jwtHelper.isExpiration(token);
        //过期返回false ,并返回504错误
        if(expiration){
            //因为不能直接返回504，所以通过字符流写出
            Result result = Result.build(null,ResultCodeEnum.NOTLOGIN);

            //使用ObjectMapper把result转成json字符串，再利用response写出
            ObjectMapper objectMapper  = new ObjectMapper();
            String json = objectMapper.writeValueAsString(result);
            response.getWriter().print(json);
            return false;
        }
        //没过期就返回true，放行
        return true;
    }
}
